import json
import re

from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.Audit_comment import Audit, Auditaaa
from utils.login_required import LoginRequiredJSONMixin
from utils.send_message import upload, url
from utils.user_check import usercheck, user_check

redis_conn = get_redis_connection()



# Create your views here.


class UserinfoView(LoginRequiredJSONMixin, APIView):
  def get(self, request):
        user = request.user
        # obj = redis_conn.get('user_info')
        # if not obj:
        obj = {
                "data": {
                    "avatar_url": url + str(request.user.avatar),
                    "create_time": str(user.last_login),
                    "mobile": user.mobile,
                    "name": user.username,
                    "user_id": user.id
                },
                "errmsg": "OK",
                "errno": "0"
            }
        return Response(obj)
        # redis_conn.set('userinfo', json.dumps(obj),ex=60*60*24)
        # return Response(obj)
import tempfile
class ProfileView(LoginRequiredJSONMixin, APIView):
    def post(self, request):
        # 获取参数
        avatar = request.data.get('avatar')
          # 将InMemoryUploadedFile对象写入临时文件
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(avatar.read())
            temp_file_path = temp_file.name
        # 调用delete_picture函数检测头像文件类型
        from utils.image import delete_picture
        avatar.seek(0)
        avatar_type = delete_picture(temp_file_path)
        if avatar_type is None:
            return Response({'errno': 400, 'errmsg': '无法确定头像文件类型'})
        # 进行判断所评论内容是否违反审核标准
        # 获取参数进行判断
        res = Auditaaa(avatar)
        if res.get('conclusion') != '合规':
            return Response({'errno': 400, 'errmsg': '头像不可以包含违规色情画面'})
        # 进行调用上传七牛云上传图片的方法，进行上传
        ret, info = upload(avatar)
        if info.status_code != 200:
            return Response('上传失败', status=201)
        # 获取需要上传的key
        request.user.avatar = ret.get('key')
        # 进行保存
        request.user.save()
        res = {
            "data": {
                "avatar_url": url + str(request.user.avatar),
                "avatar_type": avatar_type
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        }
        return Response(res)

class ChangenameView(LoginRequiredJSONMixin, APIView):
    def put(self, request):
        # 获取参数
        name = request.data.get('name')
        res = Audit(name)
        # 进行判断   所评论内容是否违反审核标准
        # 获取参数进行判断
        if res.get('conclusion') != '合规':
            return Response({'errno': 400,'errmsg':'用户名不可以包含违规内容'})
        # 进行修改和保存
        request.user.username = name
        request.user.save()
        return Response({"errno": "0", "errmsg": "修改成功"})

import thulac
# 创建thulac实例
thu1 = thulac.thulac()
class UserauthenticationView(LoginRequiredJSONMixin, APIView):
    def get(self, request):
        # 进行一个用户认证完的一个获取
        data = {'real_name': request.user.real_name, 'id_card': request.user.id_card}
        return Response({"errno": 0, "errmsg": "认证信息保存成功", 'data': data})
    def post(self, request):
        # 获取参数
        real_name = request.data.get('real_name')
        id_card = request.data.get('id_card')
        # 检查是否缺少必要参数
        if not all([real_name, id_card]):
            return Response({"errno": 300, "errmsg": "缺少必要参数"})
        # 检查身份证格式是否正确
        if not re.match(r"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9]$", id_card):
            return Response({"errno": 300, "errmsg": "身份证格式错误"})
        # 进行调用第三方进行身份认证
        aa = user_check(id_card, real_name)
        if aa is None:
            return Response({'errno': 400, 'errmsg': '身份认证失败，请输入正确的身份证信息'})
        try:
            # 判断身份是否符合认证结果
            data = json.loads(aa)
            if data.get('respMessage') == '身份证信息匹配':
                # 使用thulac对real_name进行分词
                # segmented_real_name = thu1.cut(real_name, text=True)
                # 保存认证信息到用户对象
                request.user.real_name = real_name
                request.user.id_card = id_card
                request.user.save()
                return Response({"errno": "0", "errmsg": "认证信息保存成功"})

        except Exception as e:
            print(e)
            return Response({'errno': 400, 'errmsg': '名字不符合规范'})